<%@LANGUAGE="VBSCRIPT"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>SaveTicket</title>
<!--#include file="ErrorHandler.asp" -->
<!--#include file="Includes/aspHelperFunctions.asp" -->
<% 'on error resume next %>

</head>

<body>

<table width="490" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="20" height="20" background="Images/TableUpperLeft.png">&nbsp;</td>
    <td height="20" background="Images/TableUpperMiddle.png">&nbsp;</td>
    <td width="20" height="20" background="Images/TableUpperRight.png">&nbsp;</td>
  </tr>
  <tr>
    <td width="20" background="Images/TableMiddleLeft.png">&nbsp;</td>
    <td align="center" valign="middle">Saving Ticket...Please Wait </td>
    <td width="20" background="Images/TableMiddleRight.png">&nbsp;</td>
  </tr>
  <tr>
    <td width="20" height="20" background="Images/TableLowerLeft.png">&nbsp;</td>
    <td height="20" background="Images/TableLowerMiddle.png">&nbsp;</td>
    <td width="20" height="20" background="Images/TableLowerRight.png">&nbsp;</td>
  </tr>
</table>

<%
ts=session("ticketsaved")
redir=session("redir")
currentUser = Session("CurrentUser")
'if ts=0 then
'	response.Write("ticketsaved: " & iif(isnull(ts),"(null)",ts) & " (" & TypeName(ts) & ")" & "<br>----<br>")
'else
'	response.Write("ticketsaved: " & iif(isnull(ts),"(null)",ts) & " (" & TypeName(ts) & ")" & "<br>")
'	response.Write("session('redir')): " & iif(isnull(redir),"(null)",redir) & " (" & TypeName(redir) & ")"  )
'	session("ticketsaved")=0
'	response.End()
'end if
if session("ticketsaved")<>0 then 
	response.Redirect(session("redir"))
end if

TicketID=		trim(request.Form("Ticket_ID"))
ContractID=		trim(request.Form("Contract_ID"))
Appliance=		trim(request.Form("Appliance"))
Stat=			trim(request.Form("Status"))
Emergency=		trim(request.Form("Emergency"))
Notes=			trim(request.Form("Notes"))
Notes=			replace(Notes,"'","`")
Notes=			replace(Notes,chr(34),"`")
FromDispatch=	trim(request.QueryString("FromDispatch"))
session("ticketsaved")=1

dim db,rs
set db=server.CreateObject("adodb.connection")
set rs=server.CreateObject("adodb.recordset")

FilePath=server.MapPath("access\backend\DBHub.mdb")
db.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath

'------------------------------NEW TICKET -----------------------------------
'response.Write("<br>---<br>TicketID: " & TicketID)
if (TicketID="" or isnull(TicketID)) then

	rs.open "select max(ticket_id) as maxticketid from Tkt_Tickets", db, 1, 2
	NextTicketID = rs("maxticketid") + 1
	
	if not isnumeric(NextTicketID) then NextTicketID = 1
	rs.close
	
	rs.open "select top 1 * from Tkt_Tickets", db, 1, 2
		rs.addnew
			rs("ticket_id") =		NextTicketID
			rs("Contract_ID") =		ContractID
			rs("Status") =			Stat
			rs("Created_Time") =	Now()
			rs("Appliance") =		Appliance
			rs("Emergency") =		Emergency
		rs.update
	rs.close
	
	rs.open "select max(note_id) as maxnoteid from Tkt_Ticket_History", db, 1, 2
	
	NextNoteID = rs("maxnoteid") + 1
	
	if not isnumeric(NextNoteID) then NextNoteID = 1
	rs.close

	on error goto 0

	sInsert = "insert into Tkt_Ticket_History VALUES(" & NextNoteID & "," & NextTicketID & ",'" & currentUser & "',#" & now() & "#,'" & Notes & "')"	
	db.Execute(sInsert)
	
	session("redir") = "TicketWindow.asp?Ticket_ID=" & NextTicketID & "&user=" & currentUser
	
	
	
	'----------SEND EMAIL -------------------------------------------

	set senddispatchemailrs =	server.CreateObject("adodb.recordset")
	
	Sendsql =					"select top 1 * from Admin_DispatchEmail" 
	senddispatchemailrs.open	Sendsql, db 

	send_dispatch_email =		senddispatchemailrs("send_dispatch_email_new")
	dispatch_email =			senddispatchemailrs("dispatch_email")
	
	senddispatchemailrs.close
	set senddispatchemailrs=nothing

	
	'----------- GET EMAIL SERVER --------------
	if Application("EmailServer") = "" or isnull(application("EmailServer")) then Server.Execute("GetEmailServer.asp")	
	'--------- /GET EMAIL SERVER -------------
	
	noserver = 0
	
	'send_dispatch_email=false 'temp code to stop sending emails while debuging. comment out when not debugging
	if isnull(application("EmailServer")) or application("EmailServer") = "" then noserver = 1
	
	if (send_dispatch_email = true) and (noserver=0) then
		'send mail configuration
		sch = "http://schemas.microsoft.com/cdo/configuration/" 
    
    		Set cdoConfig = CreateObject("CDO.Configuration") 
    
    		With cdoConfig.Fields 
				.Item(sch & "sendusing") =	2 ' cdoSendUsingPort 
    			.Item(sch & "smtpserver") =	application("EmailServer")  
    			.update 
    		End With 
	
	 	Set cdoMessage = CreateObject("CDO.Message") 

		set email = server.CreateObject("cdo.message")
		with email
			Set .Configuration = cdoConfig
			.subject =	"HomeSmart afterhours: New ticket"
			.from =		"Ticket_Auto_Sender"
			
			'-----make the email body
			url =		"http://" & request.ServerVariables("HTTP_HOST") & "/afterhours_test/accountticketframeset.asp" & "?FromDispatch=yes&ticketid=" & NextTicketID &"&ContractID=" & contractid & "&user=" & user
			b =			" A new ticket has been created.<br><br>"
			b = b &		"<a href='" & url & "'>Click Here To Open Ticket</a><br><br>"
			b = b &		"Ticket Number:	" & nextticketid & "<br>"
			b = b &		"Status:		" & stat & "<br>"
			b = b &		"Created Time:	" & now() & "<br>"
			b = b &		"Appliance:		" & appliance & "<br>"
			b = b &		"Is Emergency:	" & emergency & "<br>"
			b = b &		"User:	" & currentUser & "<br>"
			b = b &		"Notes:	" & notes
				
			.htmlbody = b
			.to =		dispatch_email
			set cdoconfig = nothing
		
			.Send
			
			if err.number<>0 then ErrorHandler
			set email = nothing
			set cdoConfig = nothing
		end with
	end if


'----------------------- NOT NEW TICKET SO SAVE EXISTING TICKET --------------------
else
	rs.open "select * from Tkt_Tickets where ticket_id=" & TicketID, db, 1, 2
	if rs.EOF then
		%><script type="text/javascript">alert("There Was An Error Identifying this Ticket Number\nPlease Re-Open This Ticket, Make Your Entry, And Try Saving Again.")</script>
		<%
		session("redir")="TicketWindow.asp?Ticket_ID=" & TicketID & "&user=" & currentUser
	else
		rs("Status").value =	Stat
		rs("Appliance").value =	Appliance
		rs("Emergency").value =	Emergency
		
		'IS THE WINDOW OPENED FROM DISPATCH
		if request.QueryString("FromDispatch") = "yes" then
			rs("Given_To") = request.form("GivenTo")
			
			if request.form("GivenToTime")<>"" then
				rs("Dispatched_Time") = cdate(request.Form("GivenToTime"))
			else
				rs("Dispatched_Time") = null
			end if
			
			if isnull(request.Form("followup")) then
				followupval = ""
			else
				followupval = request.Form("followup")
			end if
			
			rs("follow_up") = followupval
		end if
		
		rs.update
		
		rs.close
		
		rs.open "select max(note_id) as maxnoteid from Tkt_Ticket_History", db, 1, 2
		
		NextNoteID = rs("maxnoteid") + 1
		
		rs.close

		'rs.open "select top 1 * from Tkt_Ticket_History", db,	1,	2
		
		'rs.addnew
		'	rs("Note_ID") =		NextNoteID
		'	rs("Ticket_ID")	=	TicketID
		'	rs("User") =		currentUser
		'	rs("When") =		now()
		'	rs("Note") =		Notes
		'rs.update
		
		'rs.close
		set rs=nothing
		
		sInsert = "insert into Tkt_Ticket_History VALUES(" & NextNoteID & "," & TicketID & ",'" & currentUser & "',#" & now() & "#,'" & Notes & "')"	
		db.Execute(sInsert)
		
		session("redir") = "TicketWindow.asp?Ticket_ID=" & TicketID & "&user=" & currentUser
	
'----------SEND EMAIL -------------------------------------------
		
		set senddispatchemailrs = server.CreateObject("adodb.recordset")
	
		Sendsql = "select top 1 * from Admin_DispatchEmail" 
		senddispatchemailrs.open Sendsql, db

		send_dispatch_email = senddispatchemailrs("send_dispatch_email_existing")
		dispatch_email = senddispatchemailrs("dispatch_email")
		
		senddispatchemailrs.close
		set senddispatchemailrs=nothing
		
		'----------- GET EMAIL SERVER --------------
		if Application("EmailServer") = "" or isnull(application("EmailServer")) then Server.Execute("GetEmailServer.asp")	
		'--------- /GET EMAIL SERVER -------------
		
		noserver = 0
		
		'send_dispatch_email=false 'temp code to stop sending emails while debuging. comment out when not debugging
		if isnull(application("EmailServer")) or application("EmailServer") = "" then noserver = 1
		
		if (send_dispatch_email = true) and (noserver = 0) then
			'send mail configuration
			sch = "http://schemas.microsoft.com/cdo/configuration/" 
    
    			Set cdoConfig = CreateObject("CDO.Configuration") 
    
    			With cdoConfig.Fields 
					.Item(sch & "sendusing") =	2 ' cdoSendUsingPort 
    				.Item(sch & "smtpserver") = application("EmailServer") 
    				.update 
    			End With 


			set email = server.CreateObject("cdo.message")
			with email
				Set .Configuration = cdoConfig
				.subject =	"HomeSmart afterhours: Update to ticket#" & ticketid
				.from =		"Ticket_Auto_Sender"
				
				'-----make the email body
				url =		"http://" & request.ServerVariables("HTTP_HOST") & "/afterhours_test/accountticketframeset.asp" & "?FromDispatch=yes&ticketid=" & ticketid &"&ContractID=" &contractid & "&user=" & currentUser
				b =			"Ticket# " & ticketid & " has been modified.<br><br>"
				b = b &		"<a href='" & url & "'>Click Here To Open Ticket</a><br><br>"
				b = b &		"Ticket Number:	" & ticketid & "<br>"
				b = b &		"Status:		" & stat & "<br>"
				b = b &		"Is Emergency:	" & emergency & "<br>"
				b = b &		"User:	" & currentUser & "<br>"
				b = b &		"Notes:	" & notes
				
				.htmlbody =	b
				.to =		dispatch_email

				.Send

					
				if err.number<>0 then 
					ErrorHandler			
				end if

				set email = nothing
				set cdoconfig = nothing
			end with
		end if 'if send email=true
		
	end if 'if ticket ID was found
	
end if 'if request.form("Ticket_ID") was blank

db.close
set db=nothing

%>

<script type="text/javascript">
<%

if FromDispatch<>"yes" then 
	%>
	parent.parent.HistoryFrame.location="TicketHistory.asp?Contract_ID=<%= ContractID %>"
	<% 
else
	session("redir")=session("redir") & "&FromDispatch=yes"
end if 
%>
var redir="<%= session("redir") %>";
window.location.href=redir

</script>


</body>
</html>
